<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>登录系统测试页面</title>
    <script type="importmap">
      {
        "imports": {
          "vue": "https://unpkg.com/vue@3/dist/vue.esm-browser.js",
          "@vicons/ionicons5": "https://unpkg.com/@vicons/ionicons5@0.12.0/es/index.js",
          "naive-ui": "https://unpkg.com/naive-ui@2.40.1/es/index.js"
        }
      }
    </script>
    <link rel="stylesheet" href="https://unpkg.com/naive-ui@2.40.1/dist/index.css" />
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }

      body {
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial,
          sans-serif;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        min-height: 100vh;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 20px;
      }

      #app {
        width: 100%;
        max-width: 1200px;
      }

      .test-card {
        background: white;
        border-radius: 12px;
        padding: 24px;
        margin-bottom: 20px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
      }

      .test-card h2 {
        margin-bottom: 16px;
        color: #333;
        font-size: 20px;
        font-weight: 600;
      }

      .status-badge {
        display: inline-block;
        padding: 4px 12px;
        border-radius: 12px;
        font-size: 14px;
        font-weight: 500;
      }

      .status-logged-in {
        background: #d4edda;
        color: #155724;
      }

      .status-logged-out {
        background: #f8d7da;
        color: #721c24;
      }

      .info-item {
        padding: 8px 0;
        border-bottom: 1px solid #eee;
      }

      .info-item:last-child {
        border-bottom: none;
      }

      .info-label {
        display: inline-block;
        width: 120px;
        font-weight: 600;
        color: #666;
      }

      .info-value {
        color: #333;
      }

      .button-group {
        display: flex;
        gap: 12px;
        flex-wrap: wrap;
        margin-top: 16px;
      }
    </style>
  </head>
  <body>
    <div id="app"></div>

    <script type="module">
      import { createApp, ref, computed, watch } from 'vue'
      import {
        NButton,
        NCard,
        NSpace,
        NModal,
        NForm,
        NFormItem,
        NInput,
        NIcon,
        NSpin,
        NEmpty,
        NMessageProvider,
        createDiscreteApi,
      } from 'naive-ui'

      // 模拟 useAuth 的简化版本（实际项目中会从 composables 导入）
      function useAuthMock() {
        const isLoggedIn = ref(false)
        const userInfo = ref(null)
        const loading = ref(false)
        const showLoginModal = ref(false)

        const login = async (userId, userSecret) => {
          loading.value = true
          try {
            // 模拟 API 调用
            await new Promise((resolve) => setTimeout(resolve, 1000))

            if (userSecret.length < 6) {
              throw new Error('用户秘钥长度不能少于6位')
            }

            userInfo.value = {
              userId: userId,
              userName: `用户_${userId}`,
              loginTime: Date.now(),
            }
            isLoggedIn.value = true

            return { success: true, message: '登录成功' }
          } catch (error) {
            return { success: false, message: error.message }
          } finally {
            loading.value = false
          }
        }

        const logout = async () => {
          loading.value = true
          try {
            await new Promise((resolve) => setTimeout(resolve, 500))
            userInfo.value = null
            isLoggedIn.value = false
            return { success: true, message: '登出成功' }
          } finally {
            loading.value = false
          }
        }

        const requireAuth = () => {
          return new Promise((resolve) => {
            if (isLoggedIn.value) {
              resolve(true)
            } else {
              showLoginModal.value = true
              const unwatch = watch(isLoggedIn, (newValue) => {
                if (newValue) {
                  resolve(true)
                  unwatch()
                }
              })
            }
          })
        }

        return {
          isLoggedIn,
          userInfo,
          loading,
          showLoginModal,
          login,
          logout,
          requireAuth,
        }
      }

      const app = createApp({
        components: {
          NButton,
          NCard,
          NSpace,
          NModal,
          NForm,
          NFormItem,
          NInput,
          NIcon,
          NSpin,
          NEmpty,
          NMessageProvider,
        },
        setup() {
          const { message } = createDiscreteApi(['message'])
          window.$message = message

          const auth = useAuthMock()
          const formValue = ref({ userId: '', userSecret: '' })

          const handleLogin = async () => {
            if (!formValue.value.userId || !formValue.value.userSecret) {
              message.warning('请输入用户ID和秘钥')
              return
            }

            const result = await auth.login(formValue.value.userId, formValue.value.userSecret)
            if (result.success) {
              message.success(result.message)
              auth.showLoginModal.value = false
              formValue.value = { userId: '', userSecret: '' }
            } else {
              message.error(result.message)
            }
          }

          const handleLogout = async () => {
            const result = await auth.logout()
            if (result.success) {
              message.success(result.message)
            }
          }

          const testRequireAuth = async () => {
            const authed = await auth.requireAuth()
            if (authed) {
              message.success('已授权，可以执行操作')
            } else {
              message.warning('用户取消登录')
            }
          }

          const formatTime = (timestamp) => {
            if (!timestamp) return '-'
            return new Date(timestamp).toLocaleString('zh-CN')
          }

          return {
            auth,
            formValue,
            handleLogin,
            handleLogout,
            testRequireAuth,
            formatTime,
          }
        },
        template: `
          <n-message-provider>
            <div style="width: 100%;">
              <!-- 标题 -->
              <div class="test-card" style="text-align: center;">
                <h1 style="font-size: 32px; color: #333; margin-bottom: 8px;">登录系统测试页面</h1>
                <p style="color: #666;">测试 useAuth 组合式函数的各项功能</p>
              </div>

              <!-- 登录状态卡片 -->
              <div class="test-card">
                <h2>📊 当前登录状态</h2>
                <n-spin :show="auth.loading.value">
                  <div v-if="auth.isLoggedIn.value">
                    <span class="status-badge status-logged-in">✓ 已登录</span>
                    <div style="margin-top: 16px;">
                      <div class="info-item">
                        <span class="info-label">用户 ID：</span>
                        <span class="info-value">{{ auth.userInfo.value?.userId }}</span>
                      </div>
                      <div class="info-item">
                        <span class="info-label">用户名：</span>
                        <span class="info-value">{{ auth.userInfo.value?.userName }}</span>
                      </div>
                      <div class="info-item">
                        <span class="info-label">登录时间：</span>
                        <span class="info-value">{{ formatTime(auth.userInfo.value?.loginTime) }}</span>
                      </div>
                    </div>
                  </div>
                  <div v-else>
                    <span class="status-badge status-logged-out">✗ 未登录</span>
                    <p style="margin-top: 16px; color: #666;">请先登录以使用完整功能</p>
                  </div>
                </n-spin>
              </div>

              <!-- 操作按钮卡片 -->
              <div class="test-card">
                <h2>🎮 功能测试</h2>
                <div class="button-group">
                  <n-button 
                    type="primary" 
                    @click="auth.showLoginModal.value = true"
                    :disabled="auth.isLoggedIn.value"
                  >
                    手动打开登录弹窗
                  </n-button>
                  <n-button 
                    type="error" 
                    @click="handleLogout"
                    :disabled="!auth.isLoggedIn.value"
                    :loading="auth.loading.value"
                  >
                    退出登录
                  </n-button>
                  <n-button 
                    type="info" 
                    @click="testRequireAuth"
                  >
                    测试 requireAuth（需要登录的操作）
                  </n-button>
                </div>
              </div>

              <!-- 使用说明卡片 -->
              <div class="test-card">
                <h2>📖 测试说明</h2>
                <div style="line-height: 1.8; color: #666;">
                  <p><strong>1. 登录测试：</strong></p>
                  <ul style="padding-left: 20px; margin: 8px 0;">
                    <li>点击"手动打开登录弹窗"按钮</li>
                    <li>输入任意用户 ID</li>
                    <li>输入至少 6 位的秘钥</li>
                    <li>点击"开始登录"</li>
                  </ul>

                  <p style="margin-top: 16px;"><strong>2. requireAuth 测试：</strong></p>
                  <ul style="padding-left: 20px; margin: 8px 0;">
                    <li>在未登录状态下点击"测试 requireAuth"</li>
                    <li>会自动弹出登录框</li>
                    <li>登录成功后会显示授权成功提示</li>
                  </ul>

                  <p style="margin-top: 16px;"><strong>3. 登出测试：</strong></p>
                  <ul style="padding-left: 20px; margin: 8px 0;">
                    <li>在已登录状态下点击"退出登录"</li>
                    <li>确认状态变为未登录</li>
                  </ul>

                  <p style="margin-top: 16px; padding: 12px; background: #fff3cd; border-radius: 6px; border-left: 4px solid #ffc107;">
                    <strong>💡 提示：</strong>这是一个简化的测试页面，实际项目中会使用真实的 Chrome Storage 和完整的 useAuth 功能。
                  </p>
                </div>
              </div>

              <!-- 登录弹窗 -->
              <n-modal
                v-model:show="auth.showLoginModal.value"
                preset="card"
                title="用户登录"
                :bordered="false"
                size="medium"
                style="width: min(400px, 80vw);"
              >
                <n-form :model="formValue" size="large">
                  <n-form-item label="用户ID" path="userId">
                    <n-input
                      v-model:value="formValue.userId"
                      placeholder="请输入用户ID"
                      clearable
                    />
                  </n-form-item>
                  <n-form-item label="用户秘钥" path="userSecret">
                    <n-input
                      v-model:value="formValue.userSecret"
                      type="password"
                      placeholder="请输入用户秘钥（至少6位）"
                      show-password-on="click"
                      clearable
                    />
                  </n-form-item>
                </n-form>

                <template #footer>
                  <div style="display: flex; justify-content: flex-end; gap: 12px;">
                    <n-button @click="auth.showLoginModal.value = false">
                      取消
                    </n-button>
                    <n-button
                      type="primary"
                      :loading="auth.loading.value"
                      @click="handleLogin"
                    >
                      开始登录
                    </n-button>
                  </div>
                </template>
              </n-modal>
            </div>
          </n-message-provider>
        `,
      })

      app.mount('#app')
    </script>
  </body>
</html>

